package net.maku.jw.util;

import net.maku.jw.entity.Course;
import org.apache.commons.lang3.math.NumberUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.text.ParseException;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static net.maku.jw.util.HtmlUtil.toHtmlString;

public class StudentCourseJsoupUtil {

    /**
     *  解析课表
     *  section掌握一天的第几节上课, sectionCount=2掌握块所占高度 一次课占两节,  week=3代表星期三上课  weeks掌握哪周显示
     */
    public static List<Course> getcourseTable(String body,String studentid,String team) {
        List<Course> courseList = new ArrayList<>();

        Document document = Jsoup.parse(body);
        Element table = document.getElementById("timetable");
        Elements divkbcontent = table.select("div.kbcontent");
        String coursename = "";
        String teacher = "";
        int section = 1; //上课时间
        int week=1;//星期一
        for (Element div : divkbcontent) {
            if (week>5){
                week = 1;
                section += 2;
            }
            Elements fonts = div.select("font");
            if (fonts.size() > 0) {
                //6*7=42格子，每一格存在至少一门课
                String inforStr = div.text();
                String infoStrSplit[] = inforStr.split(" --------------------- ");
                for (int i = 0; i < infoStrSplit.length; i++) {
                    String[] info = infoStrSplit[i].split(" ");
//                    for (String s : info) {
//                        System.out.println(s);
//                    }
                    coursename = info[0].substring(0,info[0].indexOf("（"));
                    //info[0].substring(0,info[0].indexOf("（"))  //似乎没有出现“(首修)”    操作系统*（首修)    中文括号不是英文
                    //java.lang.StringIndexOutOfBoundsException: begin 0, end -1, length 9
                    teacher = info[1];
                    Course course = null;
                    //周次节数
                    String str = info[2];//"1-2,4-12(周)[01-02节]";
                    String rawWeeks = str.substring(0, str.indexOf("("));
                    List<Integer> weeks = weeks(str.substring(0,str.indexOf("(")));

                    String rawSection = HtmlUtil.getKHString(str);
                    String address = info[4];//7号楼C202
                    String last = info[5];
                    course = new Course(studentid,team,coursename,teacher,section,week,weeks,rawWeeks,rawSection,address);
                    // 课程属性  根据coursename
                    HashMap<String, String> map = setCourseAttruct(body);
                    for (Map.Entry<String, String> entry : map.entrySet()) {
                        if (entry.getKey().equals(coursename)) {
                            String[] s = entry.getValue().split(" ");
                            course.setCourseCatefory(s[0]+last);
                            course.setCourseAttribute(s[1]);
                            break;
                        }
                    }
                    courseList.add(course);
                }
                week++;

            }

        }
        return courseList;
    }


    public static void main(String[] args) throws ParseException {
//        String body = toHtmlString(new File("D:\\Code\\bishe\\maku-boot-v2.x\\maku-boot-new\\src\\main\\java\\net\\maku\\jw\\util\\xueji.html"));
        //System.out.println(getFullName(body));
        //System.out.println(getTable("C:\\JavaDemo\\htmlunit-WebClient-Demo\\src\\main\\resources\\xuanke.html"));

//        Student studentInfo = getStudentInfo(body);
//        System.out.println(studentInfo.toString());

        String body = toHtmlString(new File("D:\\Code\\bishe\\maku-boot-v2.x\\maku-boot-new\\src\\main\\java\\net\\maku\\jw\\util\\kebiao.html"));
        List<Course> courseList = getcourseTable(body,"202235710408","2023-2024-1");

//        courseList.forEach(course -> {
//            List<Integer> weeks = course.stringtoList(course.getWeekss());
//
//            course.setWeeks(course.stringtoList(course.getWeekss()));
//        });
        courseList = courseList.stream().filter(x -> x.getWeeks().get(0) <= 1).collect(Collectors.toList());
        courseList.forEach(e -> {
            System.out.println(e.toString());
        });

    }

    //还有课程属性没有填充
    public static HashMap<String,String> setCourseAttruct(String body){
        //HashMap 的 key 是不会重复的，如果有重复就会用新值覆盖旧值
        HashMap<String,String> map = new HashMap<String,String>();
        Document doc = Jsoup.parse(body);
        Elements elements = doc.body().getElementById("dataTables2").select("tr");
        for (Element e : elements) {
            Elements td1 = e.select("td");
            if (td1.size() > 0) {
                map.put(td1.get(2).text(), td1.get(6).text() + " " + td1.get(7).text());
            }
        }
//        map.forEach((k,v) -> {
//            System.out.println("key :"+ k+" value:" + v);
//        });
        return map;
    }


    /**
     * 解析周次  1-2,4-12 to   weeks=[ 1,2,4,5,6,7,8,9,10,11,12 ]
     */
    public static List<Integer> weeks(String str){
        List<Integer> weeks = new ArrayList<>();
        String[] split = str.split(",");
        for (String s : split) {
            if (s.length()>0) {
                if (NumberUtils.isCreatable(s))////需要排除 12 这种两位的情况
                    weeks.add(Integer.valueOf(s));
                else {
                    //13-14的解析  怎么识别它是两位的数字？  还是把截取变成 以-为截取吧
                    String[] intercept = s.split("-");
                    int startNum = Integer.parseInt(intercept[0]);
                    //System.out.println(startNum);
                    int endNum = Integer.parseInt(intercept[1]);
                    for (int i = startNum; i <= endNum; i++) {
                        weeks.add(i);
                    }
                }
            }
        }
        return weeks;
    }

    // 废弃  因为“09” 被识别成true
    private static final Pattern NUMBER_PATTERN = Pattern.compile("-?\\d+(\\.\\d+)?");
    public static boolean isNumeric2(String str) {
        return str != null && NUMBER_PATTERN.matcher(str).matches();
    }


}
